package common;

import java.io.Serializable;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.ArrayList;

/**
 * A class that stores salted hashed passwords, and generates and verifies challenge-response requests
 * @author sebbe
 *
 */
public class PasswordStore implements Serializable{

	private ArrayList<String> username;
	private ArrayList<String> password;
	private ArrayList<String> salt;
	private String lastChallenge;
	
	public PasswordStore(){
		username = new ArrayList<String>();
		password = new ArrayList<String>();
		salt = new ArrayList<String>();
	}
	
	public void add(String user, String pass){
		SecureRandom rand = new SecureRandom();
		byte[] s = new byte[128];
		rand.nextBytes(s);
		String newsalt = s.toString();
		
		String hash = makeHash(pass + newsalt);
		
		username.add(user);
		password.add(hash);
		salt.add(newsalt);
	}

	private String makeHash(String pass) {
		byte[] digest = null;
		try{
			MessageDigest md = MessageDigest.getInstance("SHA-256");
			md.update(pass.getBytes("UTF-8"));
			digest = md.digest();
		}catch (Exception e){
			e.printStackTrace();
		}
		String hash = new String(digest);
		return hash;
	}
	
	//generates and returns challenge
	public String challenge(){
		lastChallenge = "" + System.currentTimeMillis();
		return lastChallenge;
	}
	
	//returns the salt for a given user
	public String getSalt(String user){
		int index = username.indexOf(user);
		return salt.get(index);
	}
	
	//verifies a respone from client
	public boolean verify(String user, String response){
		int index = username.indexOf(user);
		String r = password.get(index) + lastChallenge;
		r = makeHash(r);
		return r.equals(response);
	}
	
	//comes up with a response based on a challenge and input password
	public String response(String challenge, String pass, String csalt){
		String p = makeHash(pass + csalt);
		String r = p + challenge;
		r = makeHash(r);
		return r;
	}
	
}
